/**
 * Copyright  (c) 2009-2010 Wilmar IT Service,  Inc.   
 * All  rights  reserved. 
 */
package com.wilmar.process.core.assignment;

import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.jbpm.api.model.OpenExecution;
import org.jbpm.api.task.Assignable;
import org.jbpm.api.task.AssignmentHandler;

import com.wilmar.process.core.services.spi.IUserService;
import com.wilmar.process.entity.Organization;
import com.wilmar.process.entity.OrganizationRoleCombination;
import com.wilmar.process.entity.ProcessParticipant;
import com.wilmar.process.entity.Role;
import com.wilmar.process.entity.User;

/**
 * 根据组织架构以及角色的交集查找参与人
 * 
 * @author MaKuBEX Email:makubexnet@gmail.com
 * @version 1.0.0 May 26, 2010
 * @since 1.0.0
 * 
 */
public class OrganizationRoleAssignmentHandlerImpl extends
		AbstractAssignmentHandlerImpl implements AssignmentHandler {

	/**
	 * @serialField
	 */
	private static final long serialVersionUID = -3556923686984215932L;

	private static Logger log = Logger
			.getLogger(OrganizationRoleAssignmentHandlerImpl.class);
	private Set<OrganizationRoleCombination> organizationRoleCombinationSet;

	private IUserService userService;

	/**
	 * @see org.jbpm.api.task.AssignmentHandler#assign(org.jbpm.api.task.Assignable,
	 *      org.jbpm.api.model.OpenExecution)
	 */
	public void assign(Assignable assignable, OpenExecution execution)
			throws Exception {
		ProcessParticipant participant = new ProcessParticipant();
		if (this.organizationRoleCombinationSet != null
				&& !this.organizationRoleCombinationSet.isEmpty()) {
			Set<User> allUsers = new HashSet<User>();
			for (OrganizationRoleCombination comb : this.organizationRoleCombinationSet) {
				Organization org = new Organization(comb.getOrganizationId());
				allUsers.addAll(this.userService
						.getListUsersByOrganizationAndRole(org, new Role(comb
								.getRoleId()), org.getOuterSystem()));
			}
			participant.setUserSet(allUsers);
			super.appendParticipant(assignable, participant);
			log.debug("Sending email...");
			super.sendEmail(execution, participant);
		}
	}

	/**
	 * @return the userService
	 */
	public IUserService getUserService() {
		return userService;
	}

	/**
	 * @param userService
	 *            the userService to set
	 */
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

}
